//
//  KKChatListTableViewController.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/21.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKChatListTableViewController.h"

#import "KKChatDetailViewController.h"
#import "KKUserInfoViewController.h"

#import "KKNetworkRequest+V1.h"

#import "KKConversationItem.h"
#import "KKConversationManager.h"
#import "KKMessageItem.h"
#import "FBKVOController.h"

#import "KCLabel.h"
#import "KKTopAlertView.h"

#pragma mark - KKChatListTableViewCell Class
@interface KKChatListTableViewCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UIImageView *img_header;
@property (nonatomic, weak) IBOutlet UILabel *lab_nick;
@property (nonatomic, weak) IBOutlet UILabel *lab_content;
@property (nonatomic, weak) IBOutlet UILabel *lab_time;
@property (nonatomic, weak) IBOutlet KCLabel *lab_number;

@property (nonatomic, strong) KKConversationItem *item;

@property (nonatomic, strong) FBKVOController *conversationKVO;           // 会话的KVO

@end

@implementation KKChatListTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.img_header.layer.cornerRadius = CGRectGetWidth(self.img_header.bounds)/2.0;
    self.img_header.layer.masksToBounds = true;
    
    self.lab_number.layer.cornerRadius = CGRectGetWidth(self.lab_number.bounds)/2.0;
    self.lab_number.layer.masksToBounds = true;
    
    self.lab_number.padding = UIEdgeInsetsMake(0, 5, 0, 5);
}

- (void)setItem:(KKConversationItem *)item {
    if (_item != item) {
        _item = item;
        
        [self.img_header setImageWithURL: [NSURL URLWithString: item.kk_customer.headimg] placeholderImage: nil];
        self.lab_nick.text = item.kk_customer.nick;
        
        [self configKVO];
    }
    [self updateShowMessageUI];
}

- (void)updateShowMessageUI{
    
    KKMessageItem *lastMessage = self.item.lastMessage;
    self.lab_content.text = [lastMessage.msg kk_showDescription];
    self.lab_time.text = [NSDate dateStringDifferenceNowWithTime: lastMessage.msg.timestamp andWithDetailReturn: false];
    
    NSInteger badge = self.item.badge;
    self.lab_number.hidden = badge > 0 ? false : true;
    self.lab_number.text = [NSString stringWithFormat: @"%@",@(badge)];
}

- (void)configKVO {
    [_conversationKVO unobserveAll];
    
    if (!_conversationKVO){
        _conversationKVO = [FBKVOController controllerWithObserver:self];
    }
    __weak typeof(self) weakSelf = self;
    [_conversationKVO observe:_item keyPath:@"lastMessage" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [weakSelf updateShowMessageUI];
    }];
}

@end

#pragma mark - KKChatListFooterView Class
@interface KKChatListFooterView : UIView
@end

@implementation KKChatListFooterView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        
        UIView *bgView = [[UIView alloc] initWithFrame: CGRectMake(0, CGRectGetHeight(frame)/2 - 175, CGRectGetWidth(frame), 350)];
        [self addSubview: bgView];
        {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake((frame.size.width - 140)/2.0, 50, 140, 112)];
            imageView.image = [UIImage imageNamed: @"chat_footer_tips"];
            imageView.contentMode = UIViewContentModeCenter;
            [bgView addSubview:imageView];
            
            UILabel *lab_title = [[UILabel alloc]initWithFrame: CGRectMake(0, CGRectGetMaxY(imageView.frame) + 30, CGRectGetWidth(frame), 40)];
            lab_title.font = [UIFont boldSystemFontOfSize: 18];
            lab_title.textAlignment = NSTextAlignmentCenter;
            lab_title.text = @"尚无会话";
            lab_title.textColor = [UIColor colorWithHexString: @"8190A7"];
            [bgView addSubview: lab_title];
            
            NSArray *arr_text = @[@"当在公众号上",@"有人进行咨询时这里将会",@"出现会话"];
            
            CGFloat pointY = CGRectGetMaxY(lab_title.frame);
            for (NSInteger index = 0; index < arr_text.count; index++) {
                UILabel *lab_detail = [[UILabel alloc]initWithFrame: CGRectMake(0, pointY, CGRectGetWidth(frame), 24)];
                lab_detail.font = [UIFont systemFontOfSize: 14];
                lab_detail.textAlignment = NSTextAlignmentCenter;
                lab_detail.text = arr_text[index];
                lab_detail.textColor = [UIColor colorWithHexString: @"C0C7D3"];
                [bgView addSubview: lab_detail];
                pointY += CGRectGetHeight(lab_detail.bounds);
            }
        }
    }
    return self;
}

@end



@interface KKChatListTableViewController ()

@property (nonatomic, strong) NSMutableArray *arr_conversationItems;
@property (nonatomic, strong) KKChatListFooterView *footerView;

@end

@implementation KKChatListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"客服会话";
    
    [self setRightBarButtonItemWithImageName: @"navigation_item_setting" style: UIBarButtonItemStylePlain target: self action: @selector(action_setting:)];
    
    [self private_initTableViewUI];
    
    [self configBaseInfo];
    [self private_getAllChatItems];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
    
    if (self.arr_conversationItems.count) {
        [self.tableView reloadData];
    }
}


#pragma mark -

- (void)configBaseInfo {
    
    __weak typeof(self) weakSelf = self;
    [KKConversationManager defaultManager].numberUpdateHandle = ^(NSArray *items) {
        if ([items isKindOfClass: [NSArray class]]) {
            weakSelf.arr_conversationItems = [NSMutableArray arrayWithArray: items];
        }
        [weakSelf.tableView reloadData];
    };
}

- (void)private_initTableViewUI{
    
//   self.automaticallyAdjustsScrollViewInsets = false;
    
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget: self action: @selector(private_getAllChatItems) forControlEvents: UIControlEventValueChanged];
    
    
    CGFloat spaceHeight = 64;
    if (@available(iOS 11.0, *)){
        UIWindow *window = [[UIApplication sharedApplication] delegate].window;
        if (window.safeAreaInsets.bottom > 0.0) {
            spaceHeight = 88.0;
        }
    }
    
    self.footerView = [[KKChatListFooterView alloc] initWithFrame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - spaceHeight)];
    self.tableView.tableFooterView = self.footerView;
    
    [self.tableView addSubview: self.refreshControl];
}

- (void)private_getAllChatItems{
    
    __weak typeof(self) weakSelf = self;

    [KKConversationManager sendAllConversationItemsRequest:^(BOOL success, id result) {
        
        if ([result isKindOfClass: [NSArray class]]) {
            weakSelf.arr_conversationItems = [NSMutableArray arrayWithArray: result];
        }
        
        [weakSelf.refreshControl endRefreshing];
        [weakSelf.tableView reloadData];
        
        if (!success) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf kk_showTopAlertViewWithMessage: result];
            });
        }
    }];
}

#pragma mark - Action methods
- (void)action_setting:(id)sender {
    KKUserInfoViewController *userInfoViewController = [KKUserInfoViewController viewControllerFromSB];
    [self.navigationController pushViewController: userInfoViewController animated: true];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.arr_conversationItems.count == 0) {
        tableView.tableFooterView = self.footerView;
    }
    else {
        tableView.tableFooterView = [UIView new];
    }
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arr_conversationItems.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KKChatListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KKChatListTableViewCell" forIndexPath:indexPath];
    // Configure the cell...
    
    KKConversationItem *item = [self.arr_conversationItems objectAtIndex: indexPath.row];
    [cell setItem: item];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName: @"Main" bundle: [NSBundle mainBundle]];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier: @"KKChatDetailViewController"];
    
    KKConversationItem *item = [self.arr_conversationItems objectAtIndex: indexPath.row];
    item.badge = 0;
    [(KKChatDetailViewController*)viewController setConversationItem: item];
    
    [self.navigationController pushViewController: viewController animated: true];
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //
        KKConversationItem *item = [self.arr_conversationItems objectAtIndex: indexPath.row];
        __weak typeof(self) weakSelf = self;
        
        KKNetworkRequest *request = [KKNetworkRequest request_deleteChatItem: item.identifier];
        [KKNetworking sendRequest: request responseCallBack:^(id response, NSString *error) {
            
            [weakSelf.arr_conversationItems removeObject: item];
            [weakSelf.tableView deleteRowsAtIndexPaths: @[indexPath] withRowAnimation: UITableViewRowAnimationFade];
            [KKConversationManager removeItem: item];
        }];
    }
}

@end
